import React, { useState, useEffect } from 'react';
import style from './video.module.css';
import http from '../utils/http'
import { useNavigate } from 'react-router-dom';
import { HeartOutline, MessageOutline, UploadOutline, UndoOutline } from 'antd-mobile-icons';

export default function Sp() {
    const navigate = useNavigate();
    const [videos, setVideos] = useState([]);
    const [currentVideoIndex, setCurrentVideoIndex] = useState(0); // 当前显示的视频索引
    const [isDragging, setIsDragging] = useState(false); // 是否正在拖动
    const [startY, setStartY] = useState(0); // 拖动开始的y坐标
    const [endY, setEndY] = useState(0); // 拖动结束的y坐标
    const [isLoading, setIsLoading] = useState(true); // 加载状态
    const [error, setError] = useState(null); // 错误状态

    useEffect(() => {
        getVideos();
    }, []);

    const getVideos = async () => {
        setIsLoading(true);
        setError(null);
        try {
            const res = await http.get('/videos');
            setVideos(res.data.videos || []);
        } catch (error) {
            console.error("获取视频失败:", error);
            setError("获取视频失败，请稍后重试");
        } finally {
            setIsLoading(false);
        }
    };

    // 滑动切换视频
    const handleTouchStart = (e) => {
        setIsDragging(true);
        setStartY(e.touches[0].clientY); // 记录触摸起点的y坐标
    };

    const handleTouchMove = (e) => {
        if (!isDragging) return;
        setEndY(e.touches[0].clientY); // 更新触摸终点的y坐标
    };

    const handleTouchEnd = () => {
        if (!isDragging) return;

        const deltaY = startY - endY; // 计算垂直方向的位移
        if (Math.abs(deltaY) > 50) { // 判断滑动距离是否足够大
            if (deltaY > 0 && videos.length > 0) {
                // 向上滑动 -> 下一个视频
                setCurrentVideoIndex((prevIndex) => (prevIndex + 1) % videos.length);
            } else if (deltaY < 0 && videos.length > 0) {
                // 向下滑动 -> 上一个视频
                setCurrentVideoIndex((prevIndex) => (prevIndex - 1 + videos.length) % videos.length);
            }
        }

        setIsDragging(false);
        setStartY(0);
        setEndY(0);
    };

    // 处理视频点击播放/暂停
    const handleVideoClick = (e) => {
        const video = e.target;
        if (video.paused) {
            video.play();
        } else {
            video.pause();
        }
    };

    // 处理录制新视频
    const handleRecordNew = () => {
        navigate('/video');
    };

    return (
        <div className={style.videoListContainer}>
            {isLoading ? (
                <div className={style.loadingState}>
                    <div className={style.loadingSpinner}></div>
                    <p>正在加载精彩视频...</p>
                </div>
            ) : error ? (
                <div className={style.errorState}>
                    <p>{error}</p>
                    <button onClick={getVideos} className={style.retryButton}>重试</button>
                </div>
            ) : videos.length === 0 ? (
                <div className={style.emptyState}>
                    <p>暂无视频内容</p>
                    <button onClick={handleRecordNew} className={style.recordButton}>
                        <UndoOutline /> 录制新视频
                    </button>
                </div>
            ) : (
                <div
                    className={style.spContainer}
                    onTouchStart={handleTouchStart}
                    onTouchMove={handleTouchMove}
                    onTouchEnd={handleTouchEnd}
                >
                    {/* 当前视频 */}
                    <video
                        src={`http://localhost:3001/${videos[currentVideoIndex]?.videoUrl}`}
                        loop
                        autoPlay
                        playsInline
                        onClick={handleVideoClick}
                        className={style.fullscreenVideo}
                    ></video>

                    {/* 视频信息覆盖层 */}
                    <div className={style.videoOverlay}>
                        {/* 视频进度指示器 */}
                        <div className={style.videoIndicator}>
                            {videos.map((_, index) => (
                                <div
                                    key={index}
                                    className={`${style.indicatorDot} ${index === currentVideoIndex ? style.activeDot : ''}`}
                                ></div>
                            ))}
                        </div>

                        {/* 视频互动按钮 */}
                        <div className={style.interactionButtons}>
                            <button className={style.interactionButton}>
                                <HeartOutline />
                                <span>赞</span>
                            </button>
                            <button className={style.interactionButton}>
                                <MessageOutline />
                                <span>评论</span>
                            </button>
                            <button className={style.interactionButton}>
                                <UploadOutline />
                                <span>分享</span>
                            </button>
                        </div>

                        {/* 录制新视频按钮 */}
                        <button
                            className={style.recordNewButton}
                            onClick={handleRecordNew}
                        >
                            <UndoOutline />
                        </button>
                    </div>
                </div>
            )}
              <button style={{ position: 'absolute', top: '10px', left: '10px', background: 'none', border: 'none', color: 'white', fontSize: '24px', cursor: 'pointer' ,zIndex:1000}} onClick={() => navigate('/')}>
          ✕
        </button>
        </div>
    );
}